package com.senjoeson.teamfriends.activity;

import android.app.Activity;
import android.content.Intent;
import android.graphics.drawable.ColorDrawable;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.senjoeson.teamfriends.R;
import com.senjoeson.teamfriends.bean.Friend;
import com.senjoeson.teamfriends.bean.Message;
import com.senjoeson.teamfriends.bean.MessageTypeUtils;
import com.senjoeson.teamfriends.bean.Question;
import com.senjoeson.teamfriends.bean.User;
import com.senjoeson.teamfriends.utils.ALog;
import com.senjoeson.teamfriends.utils.GlideUtils;
import com.senjoeson.teamfriends.utils.MyToast;

import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import cn.bmob.v3.BmobQuery;
import cn.bmob.v3.BmobUser;
import cn.bmob.v3.exception.BmobException;
import cn.bmob.v3.listener.FindListener;
import cn.bmob.v3.listener.QueryListener;
import cn.bmob.v3.listener.SaveListener;
import cn.bmob.v3.listener.UpdateListener;
import de.hdodenhof.circleimageview.CircleImageView;

public class AddFriendActivity extends AppCompatActivity implements View.OnClickListener {
    @BindView(R.id.portrait)
    CircleImageView mPortrait;
    @BindView(R.id.realname)
    TextView mRealname;
    @BindView(R.id.telephone)
    TextView mTelephone;
    @BindView(R.id.wechat)
    TextView mWechat;
    @BindView(R.id.city)
    TextView mCity;
    @BindView(R.id.school)
    TextView mSchool;
    @BindView(R.id.hobbies)
    TextView mHobbies;
    @BindView(R.id.sign)
    TextView mSign;
    @BindView(R.id.doSomething)
    Button mDoSomething;
    @BindView(R.id.toolbar)
    Toolbar mToolbar;
    public boolean mIsFriend = false; //是否是朋友
    public String mNickname;
    public String mUserid;
    public boolean mIsMe;
    public boolean mAddfriendflag;


    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.acitivity_addfriend);
        ButterKnife.bind(this);

        if (getSupportActionBar() != null) {
            getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        }
        if (mIsMe) {
            mToolbar.setTitle("关于我");
        } else {
            mToolbar.setTitle("用户信息");
        }
        setSupportActionBar(mToolbar);
        mUserid = getIntent().getStringExtra("userid") + "";
        mNickname = getIntent().getStringExtra("nickname") + "";
        mIsMe = getIntent().getBooleanExtra("isMe", false);
        mAddfriendflag = getIntent().getBooleanExtra("addfriendflag", false);
        User currentUser = BmobUser.getCurrentUser(User.class);
        if (mIsMe) {
            setUserData(currentUser);
        } else {
            if (mUserid.equals(currentUser.getObjectId())) {     //表示谁的好友
                mIsFriend = true;
            }
            findUserData(mUserid);
            mDoSomething.setOnClickListener(this);
        }

    }

    /**
     * 设置初始化数据
     */
    private void findUserData(String userid) {
        BmobQuery<User> userBmobQuery = new BmobQuery<>();
        userBmobQuery.getObject(userid, new QueryListener<User>() {
            @Override
            public void done(final User user, BmobException e) {
                setUserData(user);

            }
        });

    }

    /**
     * 设置用户数据
     *
     * @param user 用户
     */
    private void setUserData(User user) {
        if (user != null) {
            GlideUtils.loadImage(AddFriendActivity.this, user.getPortrait().getFileUrl(), mPortrait);
            mRealname.setText(user.getNickname());
            mCity.setText(user.getCity());
            mSchool.setText(user.getSchool());
            mSign.setText(user.getSign());
            mTelephone.setText(user.getTelephone());
            mWechat.setText(user.getWeChat());
            setDataAboutFriend(mIsMe, user, mIsFriend);
        }
    }

    /**
     * @param isMe     如果是自己
     * @param user
     * @param isFriend 是否是好友
     */
    private void setDataAboutFriend(boolean isMe, final User user, boolean isFriend) {
        if (isMe) {
            mDoSomething.setVisibility(View.GONE);
            return;
        }

        if (!isFriend) {
            mTelephone.setText("********");
            mWechat.setText("*********");
            mDoSomething.setText("添加好友");
        } else {
            mDoSomething.setText("删除好友");
            mTelephone.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Intent intent = new Intent(Intent.ACTION_DIAL);
                    Uri data = Uri.parse("tel:" + user.getTelephone());
                    intent.setData(data);
                    startActivity(intent);
                }
            });
        }
    }


    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case android.R.id.home:
                onBackPressed();
                break;
        }
        return super.onOptionsItemSelected(item);
    }


    @Override
    public void onClick(View v) {
        if (mIsFriend) {      //如果是朋友，点击就是删除逻辑
            Friend friend = new Friend();
            friend.setUserid(mUserid);
            friend.setNickname(mNickname);
            friend.delete(new UpdateListener() {
                @Override
                public void done(BmobException e) {
                    if (e == null) {
                        MyToast.showToast("删除成功");
                    } else {
                        MyToast.showToast(e.toString());
                    }
                }
            });
        } else {        //如果不是朋友，
            if (mAddfriendflag) { //检查是否有设置问题，
                BmobQuery<Question> questionBmobQuery = new BmobQuery<>();
                questionBmobQuery.addWhereEqualTo("userid", mUserid);
                questionBmobQuery.findObjects(new FindListener<Question>() {
                    @Override
                    public void done(List<Question> list, BmobException e) {
                        if (list != null && list.size() > 0) {
                            Question question = list.get(0);
                            showPopQuestionWindow(question);
                        } else {
                            ALog.d("没有设置问题");
                        }

                    }
                });


            } else {
                //没有设置问题的话  直接发送好有请求
                final User currentUser = BmobUser.getCurrentUser(User.class);
                BmobQuery<User> userBmobQuery = new BmobQuery<>();
                userBmobQuery.addWhereEqualTo("objectId", mUserid);
                userBmobQuery.findObjects(new FindListener<User>() {
                    @Override
                    public void done(List<User> list, BmobException e) {
                        if (list != null && list.size() > 0) {
                            User user = list.get(0);
                            Message message = new Message();
                            message.setSolve(false);
                            message.setUserid(currentUser.getObjectId());   //表示发送方
                            message.setOther_userid(user.getObjectId());    //表示接收方
                            message.setMessageType(MessageTypeUtils.MESSGE_APPLY_FRIEND_STATE);
                            message.setContent("您的好友" + user.getNickname() + "，加你为好友");
                            message.setMessagetime(System.currentTimeMillis());
                            message.setNickname(user.getNickname());
                            message.save(new SaveListener<String>() {
                                @Override
                                public void done(String s, BmobException e) {
                                    if (e == null) {
                                        ALog.d("保存成功");
                                        MyToast.showToast("发送成功");
                                        finish();
                                    } else {
                                        ALog.d(e.toString());
                                    }
                                }
                            });

                        }
                    }
                });
            }


        }
    }

    /**
     * 设置页面的透明度
     *
     * @param bgAlpha 1表示不透明
     */
    public static void setBackgroundAlpha(Activity activity, float bgAlpha) {
        WindowManager.LayoutParams lp = activity.getWindow().getAttributes();
        lp.alpha = bgAlpha;
        activity.getWindow().setAttributes(lp);
    }

    /**
     * 需要回答问题才能添加好友的操作
     *
     * @param question
     */
    private void showPopQuestionWindow(final Question question) {

        final View view = LayoutInflater.from(AddFriendActivity.this).inflate(R.layout.popupwindow_setquestion, null);
        final PopupWindow popupWindow = new PopupWindow(view, LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT);
        popupWindow.setFocusable(true);
        ColorDrawable dw = new ColorDrawable(-00000);
        popupWindow.setBackgroundDrawable(dw);
        setBackgroundAlpha(AddFriendActivity.this, 1f);
        popupWindow.setAnimationStyle(R.anim.anim);
        final EditText question1 = (EditText) view.findViewById(R.id.question1);
        final EditText anwser1 = (EditText) view.findViewById(R.id.anwser1);
        final EditText anwser2 = (EditText) view.findViewById(R.id.anwser2);
        final EditText question2 = (EditText) view.findViewById(R.id.question2);
        final Button mSubmit = view.findViewById(R.id.submit);
        mSubmit.setText("确认并添加好友");
        question1.setText(question.getQuestion1());
        question1.setFocusable(false);
        question2.setText(question.getQuestion2());
        question2.setFocusable(false);

        mSubmit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String answerfirst = anwser1.getText().toString().trim();
                String answerSecond = anwser2.getText().toString().trim();
                if (TextUtils.isEmpty(answerfirst) || TextUtils.isEmpty(answerSecond)) {
                    MyToast.showToast("回答答案不能为空");
                    return;
                }
                if (TextUtils.equals(answerfirst, question.getAnswer1()) && TextUtils.equals(answerSecond, question.getAnswer2())) {
                    MyToast.showToast("校验成功");
                    //添加好友操作
                    final User currentUser = BmobUser.getCurrentUser(User.class);

                    addFriend(currentUser, mUserid);
                    BmobQuery<User> userBmobQuery = new BmobQuery<>();
                    userBmobQuery.getObject(mUserid, new QueryListener<User>() {
                        @Override
                        public void done(User user, BmobException e) {
                            if (user != null) {
                                addFriend(user, currentUser.getObjectId());
                            } else {
                                ALog.d("添加失败");
                            }
                        }
                    });

                } else {
                    MyToast.showToast("回答错误，无法直接添加好友！");
                    return;
                }
                popupWindow.dismiss();
            }
        });
        popupWindow.showAtLocation(getWindow().getDecorView(), Gravity.CENTER, 0, 0);
    }

    /**
     * 把user添加到otherid的好友之中
     *
     * @param user    用户A
     * @param otherid 用户B
     */
    public void addFriend(final User user, final String otherid) {
        final Friend friend = new Friend();
        friend.setUserid(otherid);
        BmobQuery<Friend> friendBmobQuery = new BmobQuery<>();
        friendBmobQuery.addWhereEqualTo("userid", otherid);
        friendBmobQuery.addWhereEqualTo("nickname", user.getNickname());
        friendBmobQuery.findObjects(new FindListener<Friend>() {
            @Override
            public void done(List<Friend> list, BmobException e) {
                if (list == null || list.size() == 0) {
                    friend.setNickname(user.getNickname());
                    friend.setGender(user.getGender());
                    friend.setCity(user.getCity());
                    friend.setHobbies(user.getHobbies());
                    friend.setLatLng(user.getLatLng());
                    friend.setPortrait(user.getPortrait());
                    friend.setTelephone(user.getTelephone());
                    friend.setWeChat(user.getWeChat());
                    friend.save(new SaveListener<String>() {
                        @Override
                        public void done(String s, BmobException e) {
                            if (e == null) {
                                ALog.d("添加好友成功");
                            } else {
                                ALog.d(e.getMessage());
                            }

                        }
                    });
                } else {
                    ALog.d("添加失败,已存在该好友");

                }
            }
        });

    }

}
